package com.example.javabasic.suanfa.jiandan.镜像二叉树;

import com.example.javabasic.mianshi.fuzhulei.Tree;
import com.example.javabasic.mianshi.fuzhulei.TreeNode;

/**
 * 镜像二叉树
 */
public class Solution {


    public static void main(String[] args) {
        Tree tree = newTree();

        Tree jingxiang = jingxiang(tree);
        print(jingxiang);
    }

    //创建示例二叉树
    public static Tree newTree() {
        int[] arr = {8, 6, 10, 5, 7, 9, 11};
        Tree tree = new Tree(8);
        for (int i = 1; i < arr.length; i++) {
            tree = setTree(arr[i], tree);
        }
        return tree;
    }

    //插入二叉树, 二叉查找树
    public static Tree setTree(Integer val, Tree tree) {
        Tree now = tree;
        while (now != null) {
            if (now.val > val) {
                if (now.left == null) {
                    now.left = new Tree(val);
                    break;
                }
                now = now.left;
            } else {
                if (now.right == null) {
                    now.right = new Tree(val);
                    break;
                }
                now = now.right;
            }
        }
        return tree;
    }

    /**
     * 对二叉树镜像反转
     *
     * @param tree
     * @return
     */
    public static Tree jingxiang(Tree tree) {
        if (tree == null) {
            return null;
        }
        if (tree.right != null || tree.left != null) {
            //交换左右子节点
            Tree t = tree.left;
            tree.left = t.right;
            tree.right = t;
        }
        if (tree.left != null) {
            jingxiang(tree.left);
        }
        if (tree.right != null) {
            jingxiang(tree.right);
        }
        return tree;
    }

    public static TreeNode Mirror (TreeNode pRoot) {
        // write code here
        if(pRoot == null){
            return null;
        }
        if(pRoot.left!=null || pRoot.right!=null){
            TreeNode node =  pRoot.left;
            pRoot.left = pRoot.right;
            pRoot.right  = node;
        }
        if(pRoot.right!=null){
            Mirror(pRoot.right);
        }
        if(pRoot.left!=null){
            Mirror(pRoot.left);
        }
        return pRoot;
    }


    //输出二叉树 ,前序遍历
    public static void print(Tree tree) {
        if (tree == null) {
            return;
        }
        System.out.print(tree.val + " ");
        print(tree.left);
        print(tree.right);
    }

}
